package com.lbj.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbj.mall.common.utils.PageUtils;
import com.lbj.mall.common.utils.Query;
import com.lbj.mall.product.dao.SkuInfoDao;
import com.lbj.mall.product.entity.SkuImagesEntity;
import com.lbj.mall.product.entity.SkuInfoEntity;
import com.lbj.mall.product.entity.SpuInfoDescEntity;
import com.lbj.mall.product.entity.vo.AttrGroupVo;
import com.lbj.mall.product.entity.vo.SaleAttrVo;
import com.lbj.mall.product.entity.vo.SkuItemVo;
import com.lbj.mall.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            try {
                BigDecimal newMin = new BigDecimal(min);
                if (newMin.compareTo(new BigDecimal(0)) > 0) {
                    wrapper.ge("price", newMin);
                }
            } catch (Exception ignored) {
            }
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal newMax = new BigDecimal(max);
                if (newMax.compareTo(new BigDecimal(0)) > 0) {
                    wrapper.le("price", newMax);
                }
            } catch (Exception ignored) {
            }
        }

        IPage<SkuInfoEntity> iPage = page(
                new Query<SkuInfoEntity>().getPage(params), wrapper
        );
        return new PageUtils(iPage);
    }

    /**
     * 根据SpuId查询所有的sku信息
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> queryAllSkuBySpuId(Long spuId) {
        return list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    /**
     * 异步查询
     */
    @Override
    public SkuItemVo querySkuItem(Long skuId) throws Exception {
        SkuItemVo itemVo = new SkuItemVo();

        // 异步查询基本信息
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = getById(skuId);
            itemVo.setInfo(skuInfo);
            return skuInfo;
        }, executor);

        // 异步查询图片信息
        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.list(new QueryWrapper<SkuImagesEntity>()
                    .eq("sku_id", skuId));
            itemVo.setImages(skuImages);
        }, executor);

        // 异步查询详情信息
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(item -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(item.getSpuId());
            itemVo.setDesc(spuInfoDesc);
        }, executor);

        // 异步查询分组信息
        CompletableFuture<Void> groupFuture = infoFuture.thenAcceptAsync(item -> {
            List<AttrGroupVo> attrGroups = attrGroupService.getAttrWithGroupByCategoryIdAndSpuId(
                    item.getCatalogId(), item.getSpuId());
            itemVo.setGroupAttrs(attrGroups);
        }, executor);

        // 异步查询属性信息
        CompletableFuture<Void> attrFuture = infoFuture.thenAcceptAsync(item -> {
            List<SaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrBySpuId(item.getSpuId());
            itemVo.setSaleAttr(saleAttrs);
        }, executor);


        // 同时完成，一定要调用get()方法阻塞线程
        CompletableFuture.allOf(imgFuture, descFuture, groupFuture, attrFuture).get();

        return itemVo;
    }
}

























